const createError = require('http-errors');
const express = require('express');
const path = require('path');
const cookieParser = require('cookie-parser');
const logger = require('morgan');
const app = express();
const { expressjwt } = require("express-jwt");
const md5 = require("md5");
const { ForbiddenError, ServiceError, UnknownError } = require("./utils/errors");
const session = require("express-session");
// 导入设置
require("dotenv").config();
// 处理异步报错sequelize
require("express-async-errors");
// 导入数据库
require("./Dao/sync")

// 日志处理
app.use(logger('dev'));
// 请求体处理
app.use(express.json());
app.use(express.urlencoded({ extended: false }));

// cookie处理
app.use(cookieParser());
// 静态资源处理
app.use(express.static(path.join(__dirname, 'public')));

// 加入session
app.use(session({
  secret: md5(process.env.SESSION_DECREKEY),
  resave: true,
  saveUninitialized: true,
}))

//处理jwt的内容，会进行拦截所有请求查看请求头中是否带 Authorization 查看token是否过期是否有效，path是不用查看token的
app.use(expressjwt({
  secret: md5(process.env.JWT_decretKey),
  algorithms: ["HS256"],
}).unless({
  path: [
    { url: "/api/admin/login", method: "POST" },
    { url: "/api/upload", method: "POST" },
    { url: "/res/captcha", method: ["GET"] },
    { url: "/api/banner", method: ["GET", "POST"] },
    { url: "/api/comment", method: ["GET", "POST"] },
    { url: "/api/message", method: "POST" },
    { url: "/api/setting", method: "GET" },
    { url: "/api/message", method: "GET" },
    { url: "/api/project", method: "GET" },
    { url: "/api/about", method: "GET" },
    { url: "/api/blog", method: "GET" },
    { url: "/api/blogtype", method: "GET" },
    { url: /^\/api\/blog\/\d+/, method: ["GET", "PUT"] },//动态路由
  ]
}))

// 路由处理
app.use("/api/admin", require("./routes/admins"));// 管理员
app.use("/api/banner", require("./routes/banner"));//标语
app.use("/api/upload", require("./routes/upload"));//文件上传
app.use("/api/blogtype", require("./routes/blogTypes"));//文章分类
app.use("/api/blog", require("./routes/blog"));//文章
app.use("/api/project", require("./routes/project"));//项目
app.use("/api/comment", require("./routes/message"));//评论
app.use("/api/message", require("./routes/message"));//留言
app.use("/api/about", require("./routes/abouts"));//关于
app.use("/api/dashboard", require("./routes/dashborad"));//获取首页轮播图
app.use("/api/setting", require("./routes/setting"))//设置
app.use("/res/captcha", require("./routes/captcha"));//获取验证码

// catch 404 and forward to error handler
app.use(function (req, res, next) {
  next(createError(404));
});

// 错误处理
app.use(function (err, req, res, next) {
  console.log("err name", err.name);
  console.log("err message", err.message);
  if (err.name === "UnauthorizedError") {
    res.send(new ForbiddenError("未登录，或者登录已经过期").toResponseJSON());
  } else if (err instanceof ServiceError) {
    res.send(err.toResponseJSON())
  } else {
    res.send(new UnknownError().toResponseJSON());
  }
});

module.exports = app;